<script setup lang="ts">
import { ref, defineAsyncComponent, onMounted, nextTick, onUnmounted, inject, watch } from "vue";
import { eventBus } from "@/views/all/visual/template/utils";
import { useRouter } from "vue-router";

const router = useRouter();
const emits = defineEmits(["generalEvent"]);
const imgArr: Record<string, any>[] = [];
const activeName = ref("layerDepBase");
const { pipeName, setPipeName } = inject("pipeName", { pipeName: ref(), setPipeName: name => name });
let compArr = ["layerDepBase", "layerDepMech", "layerDepWater", "layerDepGas"];
let compLable = ["实景", "机械", "水科", "气化"];
const props = withDefaults(
  defineProps<{
    propValue?: {
      actionMap: Record<string, any>;
      hasHse: Boolean;
    };
  }>(),
  {
    propValue: () => ({
      actionMap: {
        layerDepBase: [],
        layerDepMech: [],
        layerDepWater: [],
        layerDepGas: [],
        layerHse: []
      },
      hasHse: false
    })
  }
);
if (props.propValue.hasHse) {
  compArr = ["layerDepBase", "layerDepMech", "layerDepWater", "layerDepGas", "layerHse"];
  compLable = ["实景", "机械", "水科", "气化", "HSE"];
}
for (let i = 0; i < compArr.length; i++) {
  let layerBase = defineAsyncComponent(() => import(`../../assets/filter/layerBase.svg?component`));
  let layerAnthor = defineAsyncComponent(() => import(`../../assets/filter/layerConduitup.svg?component`));
  let layerHse = defineAsyncComponent(() => import(`../../assets/filter/layerHse.svg?component`));
  let val = {
    comp: layerAnthor,
    name: compArr[i],
    label: compLable[i]
  };
  if (compArr[i] === "layerDepBase") {
    val.comp = layerBase;
  }
  if (compArr[i] === "layerHse") {
    val.comp = layerHse;
  }
  imgArr.push(val);
}
function camelCaseToSeparated(str, separator = "_") {
  return (
    str
      // Insert the separator before all upper case letters.
      .replace(/([a-z])([A-Z])/g, `$1${separator}$2`)
      // Convert the string to lower case.
      .toLowerCase()
  );
}

const generalEvent = item => {
  const actionMap = props.propValue.actionMap;

  if (actionMap[item.name].length == 0) return;
  activeName.value = item.name;
  setPipeName(item.name);
  compArr.forEach(name => {
    const action = actionMap[name];

    if (name === activeName.value) {
      action.forEach(id => {
        changeStyle("display", "block", id);
        changeStyle("visibility", "visible", id);
      });
    } else {
      action.forEach(id => {
        changeStyle("display", "none", id);
        changeStyle("visibility", "hidden", id);
      });
    }
  });
  // emits("generalEvent", { type: "compFilter", compEmitData: camelCaseToSeparated(item.name) });
};
onMounted(() => {
  if (router?.options?.history?.state?.forward) {
    const { pipeName: str } = parseUrlParams(router.options.history.state.forward as string) as any;
    if (str) {
      generalEvent({ name: str });
    }
  }

  eventBus.on("layerDepAction", name => {
    if (name === "onlyBtn") {
      activeName.value = "layerDepBase";
      return;
    }
    generalEvent({ name });
  });
});
function parseUrlParams(url) {
  // 提取 URL 中的查询字符串部分
  const queryParams = url.split("?")[1];

  if (!queryParams) {
    return {}; // 如果没有查询字符串，返回空对象
  }

  // 将查询字符串按 '&' 分割成数组
  const paramsArray = queryParams.split("&");
  const paramsObj = {};

  for (const param of paramsArray) {
    // 分割每个键值对
    const [key, value] = param.split("=");

    // 解码URIComponent，并处理可能的空值
    paramsObj[decodeURIComponent(key)] = value ? decodeURIComponent(value) : "";
  }

  return paramsObj;
}
onUnmounted(() => {
  eventBus.off("layerDepAction");
});
function changeStyle(styleName, value, compId = null) {
  eventBus.emit("changeStyle", { styleName, value, compId });
}
function setClass(item) {
  const actionMap = props.propValue.actionMap;
  const arr = actionMap[item.name];
  let style = {};

  if (arr.length > 0) {
    style = {
      "hover:text-[#3B82F6]": true,
      "active:text-[#3B82F6]": true,
      "text-[#3B82F6]": activeName.value === item.name,
      "text-gray-500": activeName.value !== item.name
    };
  } else {
    style = {
      "text-[#C6C6C6]": true
    };
  }
  return style;
}
</script>

<template>
  <div class="flex flex-wrap flex-col justify-start items-center bottom-[60px] rounded-[5px] overflow-hidden">
    <div
      v-for="item in imgArr"
      :key="item.name"
      class="w-[52px] h-[52px] cursor-pointer grow-0 shrink-0 bg-white flex flex-col justify-center items-center"
      :class="setClass(item)"
      @click="generalEvent(item)"
    >
      <component :is="item.comp" class="w-[24px] h-[24px]" />
      <p class="text-[11px] select-none">{{ item.label }}</p>
    </div>
  </div>
</template>
